package com.bjim.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSONObject;
import com.bjim.AResult;
import com.bjim.common.RYUtils;
import com.bjim.model.Group;
import com.bjim.model.User;
import com.bjim.model.UserGroup;

import cn.dreampie.client.Client;
import cn.dreampie.client.ClientRequest;
import cn.dreampie.client.ClientResult;
import cn.dreampie.common.http.HttpResponse;
import cn.dreampie.common.util.Maper;
import cn.dreampie.route.annotation.API;
import cn.dreampie.route.annotation.GET;
import cn.dreampie.route.annotation.POST;
import io.rong.models.CodeSuccessReslut;
import io.rong.models.GroupInfo;
import io.rong.models.TokenReslut;

@API("user")
public class UserRsource extends ApiResource{
	
	/**
	 * 用户注册
	 * @param username
	 * @param password
	 * @return
	 */
	@GET("/register")
	@POST("/register")
	public AResult register(String username,String password){
		User user=new User();
		user.set("username", username).set("password", password);
		user.save();
		System.out.println("----"+username+":"+password);
		return new AResult();
	}
	
	@GET("imgurl")
	public void getimageurl(String userid,String token) throws IOException{
		File file=new File(UserRsource.class.getResource("/").getFile()+"images/"+userid+".png");
		if(!file.exists()||file.length()==0||file.lastModified()<System.currentTimeMillis()-24*60*60*1000){
			Client client=null;//创建客户端对象
			//启动resty-example项目，即可测试客户端
			String apiUrl = "https://cloud.honycapital.com/honycloud";
			//如果不需要 使用账号登陆
			client = new Client(apiUrl);
			ClientRequest downloadRequest = new ClientRequest("/sys/struct/getUserPhoto.do?userId="+userid);
			downloadRequest.addHeader("Cookie", "iPlanetDirectoryPro="+token);
			downloadRequest.setDownloadFile(file.getPath(),true);
			ClientResult downloadResult = client.build(downloadRequest).get();
			System.out.println(downloadResult.getStatus());
		}
		getResponse().getWriter().append("api/v1.0/user/img?userid="+userid);
	}
	
	@GET("/img")
	public void images(String userid,String token) throws Exception{
		File file=new File(UserRsource.class.getResource("/").getFile()+"images/"+userid+".png");
		if(token!=null&&(!file.exists()||file.length()==0||file.lastModified()<System.currentTimeMillis()-24*60*60*1000)){
			Client client=null;//创建客户端对象
			//启动resty-example项目，即可测试客户端
			String apiUrl = "https://cloud.honycapital.com/honycloud";
			//如果不需要 使用账号登陆
			client = new Client(apiUrl);
			ClientRequest downloadRequest = new ClientRequest("/sys/struct/getUserPhoto.do?userId="+userid);
			downloadRequest.addHeader("Cookie", "iPlanetDirectoryPro="+token);
			downloadRequest.setDownloadFile(file.getPath(),true);
			ClientResult downloadResult = client.build(downloadRequest).get();
			System.out.println(downloadResult.getStatus());
		}
		if(file.length()==0){
			file=new File(UserRsource.class.getResource("/").getFile()+"images/default.png");
		}
		HttpResponse respon=getResponse();
		respon.setContentType("image/png");
		OutputStream os=respon.getOutputStream();
		FileInputStream fis=new FileInputStream(file);
		IOUtils.copy(fis, os);
		System.out.println(file.getPath());
	}
	
	public static void main(String[] args) {
		Client client=null;//创建客户端对象
		//启动resty-example项目，即可测试客户端
		String apiUrl = "https://cloud.honycapital.com/honycloud";
		//如果不需要 使用账号登陆
		client = new Client(apiUrl);
		ClientRequest downloadRequest = new ClientRequest("/sys/struct/getUserPhoto.do?userId=edcb4b04-d431-4e60-8ce6-3cbe44959ad3");
		downloadRequest.addHeader("Cookie", "iPlanetDirectoryPro=AQIC5wM2LY4Sfcx-lfbqmqFPxfm-co-bBX4gm0zo98gy7qc.*AAJTSQACMDIAAlNLABQtNjg4ODQxMzI0NTc1NzE3ODk4NwACUzEAAjAz*");
		downloadRequest.setDownloadFile(UserRsource.class.getResource("/").getFile()+"images/edcb4b04-d431-4e60-8ce6-3cbe44959ad3.png",true);
		ClientResult downloadResult = client.build(downloadRequest).get();
		System.out.println(downloadResult.getStatus());
		System.out.println(UserRsource.class.getResource("/").getFile());
	}
	
	/**
	 * 用户登录
	 * @param account
	 * @param password
	 * @return
	 */
	@GET("/login")
	@POST("/login")
	public AResult login(String account,String password){
		return new AResult(User.dao.login(account, password));
	}
	
	/**
	 * 用户退出
	 * @param userid
	 * @return
	 */
	@GET("/:userid/loginout")
	@POST("/:userid/loginout")
	public AResult login(String userid){
		return new AResult();
	}
	
	/**
	 * 获取用户融云token
	 * @param userid
	 * @return
	 */
	@GET("/:userid/token")
	@POST("/:userid/token")
	public AResult getToken(String userid){
		User user=User.dao.findById(userid);
		String username=user.get("username");
		String portrait_uri=user.getStr("portrait_uri");
		
		System.out.println(userid);
		Map<String, String>  tokenMap=Maper.of();
		try {
			TokenReslut token=RYUtils.RyUser.getToken(String.valueOf(userid), username, portrait_uri);
			tokenMap.put("token", token.getToken());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AResult(tokenMap);
	}
	
	/**
	 * 设置用户头像
	 * @param userid
	 * @param uri
	 * @return
	 * @throws Exception
	 */
	@GET("/:userid/set_portrait_uri")
	@POST("/:userid/set_portrait_uri")
	public AResult getPortraitUri(String userid,String uri) throws Exception{
		User user=User.dao.findById(userid);
		user.set("portrait_uri", uri).update();
		CodeSuccessReslut  result=RYUtils.RyUser.refresh(String.valueOf(userid), user.getStr("username"), uri);
		if(result.getCode()==200){
			
		}
		return new AResult(user.remove("password"));
	}
	
	/**
	 * 获取用户群组列表
	 * @param userid
	 * @return
	 */
	@GET("/:userid/groups")
	@POST("/:userid/groups")
	public AResult getUserGroups(String userid){
		List<Group> groups=new User().set("userid", userid).findGroups();
		GroupInfo[] gifs=new GroupInfo[groups.size()];
		for(int i=0;i<groups.size();i++){
			Group gp=groups.get(i);
			gifs[i]=new GroupInfo(gp.get("groupid").toString(), gp.getStr("groupname"));
		}
		try {
			RYUtils.RyGroup.sync(String.valueOf(userid), gifs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AResult(groups);
	}
	
	/**
	 * 设置群组置顶
	 * @param userid
	 * @param groupid
	 * @param istop
	 * @return
	 */
	@GET("/:userid/setgrouptop")
	public AResult setGroupTop(String userid,int groupid,int istop){
		UserGroup.dao.update(" update ts_usergroup set istop=? where userid=? and groupid=?" ,istop, userid,groupid);
		return new AResult();
	}
	
	/**
	 * 获取用户信息
	 * @param userid
	 * @return
	 */
	@GET("/:userid")
	@POST("/:userid")
	public AResult getUser(String userid){
		System.out.println(userid);
		User user=User.dao.findById(userid).remove("password");
		user.set("adUser", JSONObject.parse(user.getStr("adUser")));
		user.set("userExts", JSONObject.parse(user.getStr("userExts")));
		user.set("hrEmployee", JSONObject.parse(user.getStr("hrEmployee")));
		return new AResult(user);
	}
	
	/**
	 * 根据用户名查找用户
	 * @param username
	 * @return
	 */
	@GET("/find/:username")
	@POST("/find/:username")
	public AResult findUser(String username){
		return new AResult(User.dao.findByUsername(username));
	}
	
}
